package com.gientech.redisdemo.util;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisUtil {
    @Autowired
    RedisTemplate redisTemplate;
    public Object get(String key){
        return key==null?null:redisTemplate.opsForValue().get(key);
    }


    public boolean set(String key,Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

/**
 * Author liziyang
 * @Description 添加缓存并设置过期时间
 * Date 13:33 2022/5/31
 * @Param  [key, 键
 *          value 值
 *          time 时间(秒) time要大于0 如果time<=0 将设置无期限]
 *return boolean true成功 false失败
 */
 public boolean set(String key, Object value, long time){
     try{
         if(time>0){
             redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
         }else{
             set(key, value);
         }
         return true;
     } catch (Exception e) {
         e.printStackTrace();
         return false;
     }
 }

    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
 public boolean hasKey(String key){
     try{
         return  redisTemplate.hasKey(key);
     } catch (Exception e) {
         e.printStackTrace();
         return false;
     }
 }
/**
 * 根据key 获取过期时间
 * @param key 键 不能为null
 * @return 时间（秒）返回0 代表为永久有效
 */

public long getExpire(String key) {
    return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
}
